package com.dw.etl.core.utils;

import com.dw.etl.common.base.BaseException;
import com.dw.etl.common.util.LocalDateUtil;
import com.dw.etl.core.bean.model.BaseDbTpcomp;
import com.dw.etl.core.bean.vo.JobQryVO;
import com.dw.etl.core.bean.vo.TableVO;
import com.dw.etl.core.config.EtlConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.core.JobParametersBuilder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by liujunlei on 2021/5/25.
 */
public class EtlUtil {
    /**
     * 只适用于单表逻辑，请将主表放from后
     * 提取fields字段逻辑为从select至from之间的字符串，逗号分割
     * 提取表名的逻辑为紧挨from后的字符串
     * @param sql
     */
    public static TableVO findTbsAndFldsFromSql(String sql) {
        sql = sql.toUpperCase();
        int firstSelect = sql.indexOf("SELECT");
        int firstFrom = sql.indexOf("FROM");
        String fields = sql.substring(firstSelect+6,firstFrom);
        sql = sql.substring(firstFrom+4).trim();
        String tableName;
        if(sql.indexOf(" ")>0) {
            tableName = sql.substring(0,sql.indexOf(" "));
        } else {
            tableName = sql.substring(0,sql.length());
        }
        TableVO tableVO = new TableVO();
        tableVO.setFields(fields.split(","));
        tableVO.setTableName(tableName);
        return tableVO;
    }

    public static void main(String argus[]) {
        findTbsAndFldsFromSql(null);
    }

    public static Date getDate(String d,Integer euDtDim) throws BaseException {
        Date date = null;
        try {
            switch (euDtDim) {
                case 3: //天
                    date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,8)+" 00:00:00");
                    break;
                case 4: //月
                    date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,6)+"01 00:00:00");
                    break;
                case 5: //季
                    int month = 3*(Integer.parseInt(d.substring(4,5))-1)+1;
                    if(month<12 && month>0) {
                        String sm = month>9?(month+""):("0"+month);
                        date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,4)+sm+"01 00:00:00");
                    }
                    break;
                case 6: //年
                    date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,4)+"0101 00:00:00");
                    break;
            }
        } catch (Exception e) {
            throw new BaseException("时间格式转换错误");
        }
        if(date==null) {
            throw new BaseException("时间转换失败");
        }
        return date;
    }

    public static Date getNextDate(Date date,Integer euDtDim) throws BaseException {
        Date nextDate = null;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            switch (euDtDim) {
                case 3: //天
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    break;
                case 4: //月
                    calendar.add(Calendar.MONTH, 1);
                    break;
                case 5: //季
                    calendar.add(Calendar.MONTH, 3);//增加三个月
                    break;
                case 6: //年
                    calendar.add(Calendar.YEAR, 1);
                    break;
            }
            nextDate = new Date(calendar.getTimeInMillis());
        } catch (Exception e) {
            throw new BaseException("时间格式转换错误");
        }
        return nextDate;
    }

    public static String getInsertSqlByMap(Map<String,Object> data,String tableName) {
        String sql ="insert into "+tableName+"(";
        String values = " values (";
        for(String field:data.keySet()) {
            sql+=(field+",");
            values += (":"+field+",");
        }
        sql = sql.substring(0,sql.length()-1)+")";
        values = values.substring(0,values.length()-1)+")";
        return sql+values;
    }

    public static String extrCharFromString(String str,String begin,String end) {
        int b = str.indexOf(begin);
        int e = str.indexOf(end);
        if(b>0 && e>0) {
            return str.substring(b+begin.length(),e);
        }
        return null;
    }

    /**
     * 根据标准类型获取对应数据库数据类型
     * @param dbTpcompList
     * @param euType
     * @param numLength
     * @param numPrec
     * @return
     */
    public static String getDbTypeByStandType(List<BaseDbTpcomp> dbTpcompList,String euType,Long numLength,int numPrec) {
        for (BaseDbTpcomp comp : dbTpcompList) {
            if (euType.equals(comp.getEuJavatp())) {
                if (numPrec > 0 && comp.getFgDeci() > 0) { //小数
                    if (numLength < comp.getNumLength()) {
                        return comp.getEuFldtp() + "(" +numLength+ "," + numPrec + ")";
                    }
                } else if (numPrec == 0 && comp.getFgDeci() == 0) {
                    if (numLength < comp.getNumLength()) {
                        return comp.getEuFldtp() + "(" +numLength+")";
                    }
                }
            }
        }
        return null;
    }

    public static void addDayParameter(String dateNow,JobParametersBuilder parametersBuilder) {
        try {
            String strDateEnd = dateNow+" 00:00:00";
            Date dateEnd = LocalDateUtil.dateFormat.parse(strDateEnd);
            Date dateBegin = LocalDateUtil.dateCalculate(dateEnd,Calendar.DAY_OF_MONTH,-1);//昨天开始时间
            String dBegin = LocalDateUtil.dayFormat.format(dateBegin);
            String dEnd = LocalDateUtil.dayFormat.format(dateEnd);
            parametersBuilder.addString(EtlConstant.DATE_BEGIN,LocalDateUtil.dateFormat.format(dateBegin));
            parametersBuilder.addString(EtlConstant.DATE_END,strDateEnd);
            parametersBuilder.addString(EtlConstant.DATE_NOW,dateNow+" "+LocalDateUtil.timeFormat.format(new Date()));
            parametersBuilder.addString(EtlConstant.DIM_DAY_BEGIN,dBegin);
            parametersBuilder.addString(EtlConstant.DIM_DAY_END,dEnd);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
